package com.java.filter;

import com.java.bean.Message;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"/admin/views/*", "/admin/index.html", "/admin"})
public class AccessControllerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) servletRequest;
        final HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        final Object admin = req.getSession().getAttribute("admin");
        if (admin != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else if (uri.startsWith("/admin/views") && uri.endsWith(".html")) {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write("<script>top.location.href='/admin/login.html'</script>");
        } else if (!uri.endsWith(".do")) {
            resp.sendRedirect("/admin/login.html");
        } else {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(new Message(-404, "请先登录").toJSON());
        }
    }

    @Override
    public void destroy() {

    }
}
